<?php
/*********************************************************************************************************************
creatTm.php

usage:				creatTm.php is used in conjunction with an ajax call using the http post method to get the availability of the 
							team members sent in via the QMAIL parameter during the date range established by the STARTDATE and ENDDATE parameters
 							
required params: 
	members:		a list of email addresses of the team members that are to be associated with this team separated with the | (pipe) character 
	teamname: 	The name of the team that will be created
	
returns an integer code using the following scheme:
								0 - unsuccesful attempt, database error?
								1 - succesfully added team and coresponding members
								2 - teamname exists
*********************************************************************************************************************/
	
	require_once "dBConnect.php";
	require_once "calendars.php";
	
	$db = new dBConnect();
	$members =  split("\|", trim($_POST['members'], "\|"));
	$teamname = $_POST['teamname'];
	$safe_teamname = htmlentities($_POST['teamname'], ENT_QUOTES);
	$summary = "Team calendar for ".$teamname;
	$color = $_POST['teamCalendarColor'];

	//insert team into database if team exists echo 2
	if(count($db->getData("*", "teams", "teamname='$safe_teamname'")) > 0){
		echo 2;
		return;
	}
	
	$team_id = $db->insert("'','$safe_teamname'", "teams", true);
	//now map each teammember to the team
	if($team_id){
	
		//create the calendar
		createCalendar($client,$teamname, $summary);
		
		//need to get the calendarid for new calendar not sure of a faster way for now but this should work
		$gdataCal = new Zend_Gdata_Calendar($client);
		$calFeed = $gdataCal->getCalendarListFeed();
		
		foreach($calFeed as $calendar){
			if($calendar->title->text == $teamname){
				$id = $calendar->id->text;
				$cal = str_replace(Zend_Gdata_Calendar::CALENDAR_FEED_URI.'/default/', "", $id);
				break;
				}
		}	
		
		foreach($members as $member){
			$mem = split(":", $member);
			shareCalendar($client, $cal, $mem[0], $mem[1]);	
			$db->insert($team_id.", '$mem[0]'", 'team_members');
		}
	
		echo 1;
	}else//unsuccesfull attempt
		echo 0;
	
?>